package com.spring.framework.config.autowired.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 注解 @Autowired标注在构造器上时，表示对该构造器的所有参数从IoC中查找匹配的对象注入进去，查找的类型就是参数类型，查找的name就是参数名。
 *
 * @author xuweizhi
 * @since 2020/12/15 10:37
 */
@Component
public class AutowiredConstructorDemo {

	private DemoA demoA;

	private DemoB demoB;

	@Autowired(required = false)
	public AutowiredConstructorDemo(DemoA demoA, DemoB demoB) {
		System.out.println("demoA"+"demoB");
		this.demoA = demoA;
		this.demoB = demoB;
	}

	/**
	 * 添加只有demoA参数的构造器，并且作为候选构造器
	 */
	@Autowired(required = false)
	public AutowiredConstructorDemo(DemoA demoA) {
		this.demoA = demoA;
	}



	public AutowiredConstructorDemo() {
	}

	@Component("demoA")
	public static class DemoA {
		public DemoA() {
			System.out.println("DemoA："+this);
		}
	}

	/**
	 * 如果我们想要一种能找到就注入，找不到就不注入的情况，那么我们可以设置@Autowired注解的required属性为false（默认为true），
	 * 为false就表示构造构造器上的参数都是非必须的依赖，这样即使找不到依赖项也不会报错！
	 */
	@Component("demoB")
	public static class DemoB extends DemoA {
		public DemoB() {
			System.out.println("DemoB："+this);
		}
	}

	@Override
	public String toString() {
		return "AutowiredConstructorDemo{" +
				"demoA=" + demoA +
				", demoB=" + demoB +
				'}';
	}
}
